﻿#region 命名空间

using System;
using System.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using WinnerCMS.BLL;
using WinnerCMS.Common;
using WinnerCMS.Model;
using WinnerCMS.Model.Attribute;
using WinnerCMS.Model.Enum;

#endregion

namespace WinnerCMS.WebUI.Admin.Soft
{
    /// <summary>
    ///     软件录入
    /// </summary>
    [Access("ContenAdd,ContenEdit")]
    public partial class Add : WebFactory.PageBase
    {
        private SoftManage _myBll;
        private readonly CategoryManage _mySoftBll = new CategoryManage();


        private byte ModelId;

        /// <summary>
        ///     自定义字段
        /// </summary>
        protected bool ExtendField;


        protected void Page_Load(object sender, EventArgs e)
        {
            InitEveryPost();


            if (!IsPostBack)
            {
                InitUI();
                this.txtUpDateTime.Text = DateTime.Now.ToString();
                BindDropDownList();

                if (Request["ID"] != null) //修改软件界面
                {
                    EidtUI();
                }
                else //添加软件界面
                {
                    AddUI();
                }
            }
        }

        private void InitEveryPost()
        {
            this.ModelId = byte.Parse(Request["ModelId"]);

            this._myBll = PolicyInjection.Create<SoftManage>();

            new SoftServerManage().BindDDL(this.DownLoadServer, "", this.ModelId);

            new FieldObject(this.ModelId).LoadUI(this.T_DefinedFile, out this.ExtendField);
        }


        private void BindDropDownList()
        {
            ServerControl.BindDropDownList(this.ddlRank, new RoleManage().BindList(false), "RoleName", "ID",
                new ListItem { Text = "<请选择>", Value = "0" });
            this._mySoftBll.BindDDL(this.ddlCategory, BindOption.NoLink, "<请选择栏目>", this.ModelId);

            new SpecialManage().BindDDL(this.ddlSpecialID, BindOption.NoLink, "<请选择专题>", this.ModelId);
        }

        #region 初始化界面

        /// <summary>
        ///     初始化界面
        /// </summary>
        private void InitUI()
        {
            this.trAuthor.Visible = FieldControl.Enabale("Author");
            this.trBlackGuard.Visible = FieldControl.Enabale("BlackGuard");
            this.trBrief.Visible = FieldControl.Enabale("Brief");
            this.trCopyrightType.Visible = FieldControl.Enabale("CopyrightType");
            this.trDecompressPassword.Visible = FieldControl.Enabale("DecompressPassword");
            this.trDemoUrl.Visible = FieldControl.Enabale("DemoUrl");
            this.trEmail.Visible = FieldControl.Enabale("Email");
            this.trHits.Visible = FieldControl.Enabale("Hits");
            this.trHomepage.Visible = FieldControl.Enabale("Homepage");
            this.trTemplateFileName.Visible = FieldControl.Enabale("TemplateFileName");
            this.trPicUrl.Visible = FieldControl.Enabale("PicUrl");

            this.trPointNum.Visible = FieldControl.Enabale("PointNum");
            this.trRank.Visible = FieldControl.Enabale("Rank");
            this.NtxtPointNum.Visible = FieldControl.Enabale("PointNum");
            this.trRunAtSystem.Visible = FieldControl.Enabale("RunAtSystem");
            this.trSoftLanguage.Visible = FieldControl.Enabale("SoftLanguage");
            this.trSoftSize.Visible = FieldControl.Enabale("SoftSize");
            this.trSoftType.Visible = FieldControl.Enabale("SoftType");
            this.trSoftVersion.Visible = FieldControl.Enabale("SoftVersion");
            this.trStars.Visible = FieldControl.Enabale("Stars");
            this.trUpDateTime.Visible = FieldControl.Enabale("UpDateTime");

            this.trSpecialID.Visible = FieldControl.Enabale("SpecialID");

            //////////////////////////////////////////


            if (FieldControl.Enabale("IncludePic") == false)
            {
                this.cbkIncludePic.Visible = false;
                this.cbkIncludePic.Checked = true;
            }
            if (FieldControl.Enabale("AllowComment") == false)
            {
                this.cbkAllowComment.Visible = false;
                this.cbkAllowComment.Checked = true;
            }
            this.cbkIsSlide.Visible = FieldControl.Enabale("IsSlide");
        }

        #endregion

        protected string AutoTitle()
        {
            if (Request["ID"] != null) //修改界面
            {
                return "修改" + ModelManage.GetContentName(this.ModelId);
            }
            return "添加" + ModelManage.GetContentName(this.ModelId);
        }

        #region 添加界面

        /// <summary>
        ///     修改界面
        /// </summary>
        private void AddUI()
        {
            this.btnSoftAdd.Visible = true;
            this.btnSoftEdit.Visible = false;

            var config = CMSConfig.Instance();
            var arrStr = config.Soft.RunAtSystem;
            foreach (ListItem cb in this.CBL_RunAtSystem.Items)
            {
                foreach (var str in arrStr)
                {
                    if (cb.Value == str)
                    {
                        cb.Selected = true;
                    }
                }
            }
        }

        #endregion

        #region 修改界面

        /// <summary>
        ///     修改界面
        /// </summary>
        private void EidtUI()
        {
            this.btnSoftAdd.Visible = false;
            this.btnSoftEdit.Visible = true;

            var model = this._myBll.GetInfo(int.Parse(Request["ID"]));

            this.ddlCategory.SelectedValue = model.CategoryId.ToString();
            this.ddlSoftLanguage.SelectedValue = model.SoftLanguage;
            this.ddlSoftType.SelectedValue = model.SoftType;
            this.txtSoftName.Text = model.ContentTitle;
            this.txtSoftVersion.Text = model.SoftVersion;
            this.txtSoftSize.Text = model.SoftSize;
            this.txtKey.Text = model.Tags;

            this.ddlStars.SelectedValue = model.Stars.ToString();
            this.ddlCopyrightType.SelectedValue = model.CopyrightType;
            try
            {
                var arrStr = model.RunAtSystem.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (ListItem cb in this.CBL_RunAtSystem.Items)
                {
                    foreach (var str in arrStr)
                    {
                        if (cb.Value == str)
                        {
                            cb.Selected = true;
                        }
                    }
                }
            }
            catch
            {
                MsgBox.Message("加载软件运行平台的时候错误，请重新勾选。", this);
            }

            this.txtBrief.Text = model.Brief;
            this.txtAuthor.Text = model.Author;
            this.txtEmail.Text = model.Email;

            this.cbkIncludePic.Checked = model.IncludePic;
            this.cbkIsSlide.Checked = model.IsSlide;
            this.cbkAllowComment.Checked = model.AllowComment;
            this.cbkIsHeadline.Checked = model.IsHeadline;
            this.cbkIsOnTop.Checked = model.IsOnTop;
            this.cbkIsElite.Checked = model.IsElite;
            this.cbkIsChecked.Checked = model.IsChecked; ;
            //cbkIsDraft.Checked = model.IsDraft == 1 ? true : false;

            this.txtHomepage.Text = model.Homepage;
            this.txtDemoUrl.Text = model.DemoUrl;
            this.txtPicUrl.Text = model.PicUrl;
            this.txtDecompressPassword.Text = model.DecompressPassword;
            this.CC_Content.Text = HTML.Html2Text(model.Content);
            this.ddlBlackGuard.SelectedValue = model.BlackGuard;
            this.ddlRank.SelectedValue = model.Rank.ToString();

            this.NtxtPointNum.Text = model.PointNum.ToString();
            this.NtxtHits.Text = model.Hits.ToString();
            this.txtTemplateFileName.Text = model.TemplateFileName;

            this.hfDownList.Value = SerializableHelper.SerializeToString(
                new SoftDownListManage().ShowDownList(model.Id), DataFormart.Json);

            #region 自定义字段

            string strErr = null;
            new FieldManage().ExtendFieldData(this.ModelId, false, Request["ID"], this.T_DefinedFile, ref strErr);
            if (string.IsNullOrEmpty(strErr) == false)
                MsgBox.Message(strErr.Replace("'", "\\'"), this);

            #endregion
        }

        #endregion

        protected void btnSoftAdd_Click(object sender, EventArgs e)
        {
            if (CategoryManage.CheckAllowCategory(int.Parse(this.ddlCategory.SelectedValue)) == false)
            {
                MsgBox.Message("您没有该栏目的录入权限！", this);

                return;
            }
            if (this.CBL_RunAtSystem.SelectedItem == null)
            {
                MsgBox.Message(" 请选择软件平台！", this);
                return;
            }
            var model = new WinnerCMS.Model.Soft
            {
                CategoryId = int.Parse(this.ddlCategory.SelectedValue),
                SoftLanguage = this.ddlSoftLanguage.SelectedValue,
                SoftType = this.ddlSoftType.SelectedValue,
                ContentTitle = this.txtSoftName.Text.Trim(),
                SoftVersion = this.txtSoftVersion.Text.Trim(),
                SoftSize = this.txtSoftSize.Text.Trim(),
                Stars = byte.Parse(this.ddlStars.SelectedValue),
                CopyrightType = this.ddlCopyrightType.SelectedValue
            };

            var winner = new MyStringBuilder();
            foreach (ListItem cb in this.CBL_RunAtSystem.Items)
            {
                if (cb.Selected)
                {
                    winner.Append(cb.Value);
                    winner.Append(",");
                }
            }
            winner.TrimEnd();
            model.RunAtSystem = winner.ToString();
            model.Tags = this.txtKey.Text.Trim();
            if (model.Tags.Length == 0)
            {
                model.Tags = this.txtSoftName.Text.Trim();
                model.Tags = model.Tags.Replace(" ", "|");
            }

            model.IncludePic = this.cbkIncludePic.Checked;
            model.IsSlide = this.cbkIsSlide.Checked;
            model.AllowComment = this.cbkAllowComment.Checked;
            model.IsHeadline = this.cbkIsHeadline.Checked;
            model.IsOnTop = this.cbkIsOnTop.Checked;
            model.IsElite = this.cbkIsElite.Checked;

            model.IsChecked = this.cbkIsChecked.Checked;
            model.IsDraft = this.cbkIsDraft.Checked;

            model.Author = this.txtAuthor.Text.Trim();
            model.Email = this.txtEmail.Text.Trim();
            model.Homepage = this.txtHomepage.Text.Trim();
            model.DemoUrl = this.txtDemoUrl.Text.Trim();
            model.DecompressPassword = this.txtDecompressPassword.Text.Trim();
            model.Brief = this.txtBrief.Text.Trim();
            model.Content = this.CC_Content.Text;
            model.PicUrl = this.txtPicUrl.Text.Trim();
            model.Editor = UserManage.Current.UserName;
            model.BlackGuard = this.ddlBlackGuard.SelectedValue;
            model.Rank = short.Parse(this.ddlRank.SelectedValue);
            model.PointNum = short.Parse(this.NtxtPointNum.Text.Trim());
            model.Hits = int.Parse(this.NtxtHits.Text.Trim());
            model.UpdateTime = DateTime.Parse(this.txtUpDateTime.Text);
            model.TemplateFileName = this.txtTemplateFileName.Text.Trim();

            Result res;
            if (Request["ID"] == null)
            {
                model.Id = 0;

                res = new SoftManage().Add(model);
                if (string.IsNullOrEmpty(res.Errors) == false)
                {
                    MsgBox.Message(res.Errors, this);
                    return;
                }
            }
            else
            {
                model.Id = int.Parse(Request["ID"]);
                res = new SoftManage().Add(model);
                if (string.IsNullOrEmpty(res.Errors) == false)
                {
                    MsgBox.Message(res.Errors, this);
                    return;
                }
            }

            var downLoadServers = Request.Form["DownLoadServer"];
            var fileNames = Request.Form["FileName"];
            res = new SoftDownListManage().Add(this.ModelId, model.Id, downLoadServers, fileNames);
            if (string.IsNullOrEmpty(res.Errors) == false)
            {
                MsgBox.Message(res.Errors, this);
                return;
            }

            Response.Redirect(string.Format("../Common/SaveOK.aspx?ModelId={0}&ID={1}", this.ModelId, model.Id));
        }
    }
}